'''
需要ans = res = ListNode(0)的原因是，保留好原本的头节点，不然返回的就是最后一个值，因为遍历以后，链表指针就到了末尾。
'''



# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        # if not list1:
        #     return list2
        # if not list2:
        #     return list1
        ans = res = ListNode(0)
        while list1 and list2:
            if list1.val > list2.val:
                res.next = list2
                list2 = list2.next
            else:
                res.next = list1
                list1 = list1.next
            res = res.next
        res.next = list1 if list1 else list2
        return ans.next